<template>
	<div class="container">
		<!-- 内容卡片视图区域 -->
		<el-card>
			<!-- 列表区域 -->
			<el-table :data="roles" style="width: 100%" highlight-current-row>
				<!-- 展开行 -->
				<el-table-column type="expand">
					<template slot-scope="scope">{{scope.row}}</template>
				</el-table-column>
				<!-- 基本信息 -->
				<el-table-column prop="rid" label="角色ID" width="80" />
				<el-table-column prop="title" label="角色名称">
					<template slot-scope="scope">
						<el-input
							v-model="scope.row.title"
							placeholder="请输入角色名称"
							:disabled="scope.row.disabled"
							@change="scope.row.changed = true"
							@blur="handleInputBlur(scope.row)"
						/>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="是否启用" width="80">
					<template slot-scope="scope">
						<el-switch
							:disabled="scope.row.disabled"
							v-model="scope.row.status"
							active-color="#13ce66"
							inactive-color="#ff4949"
							@change="handleSwitchChange(scope.row)"
						></el-switch>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
	</div>
</template>

<script>
	import _ from "lodash";
	import editRoleRules from "./form-rules/editRoleRules";

	export default {
		name: "roles-list",
		data() {
			return {
				editRoleRules,
				roles: []
			};
		},
		created() {
			this.getRoles();
		},
		methods: {
			// 获取所有角色列表信息
			async getRoles() {
				const res = await this.$http.get("/roles");
				if (!res) return;
				// 为每个角色对象新增绑定属性
				this.roles = res.map(role => {
					role.changed = false;
					role.disabled = false;
					return role;
				});
				// 使超管账户不可被编辑
				this.roles.find(role => role.rid === 0).disabled = true;
			},
			// 发送请求修改角色名称
			async commitRole(role) {
				// role.disabled = true;
				await this.$http.put(`/roles/${role.rid}`, role, true);
				// role.disabled = false;
			},
			// 发送请求批量修改角色名称
			async commitRoles(roles) {
				await this.$http.put(`/roles`, roles, true);
			},
			async handleInputBlur(role) {
				role.changed && (await this.commitRole(role));
				role.changed = false;
			},
			handleSwitchChange(role) {
				this.commitRole(role);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.row-confirm {
		margin-top: 20px;
		display: flex;
		justify-content: center;
		.el-button {
			margin: 0 50px;
		}
	}
</style>
